package com.zhumo.sz.common.http;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.sun.xml.internal.ws.policy.privateutil.PolicyUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import sun.security.x509.IPAddressName;

import javax.jws.Oneway;
import javax.print.attribute.standard.PresentationDirection;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Objects;

/**
 * @comment 封装Http请求相关操作 基于Alibiba HttpClient
 * @author zhumo
 */
@Slf4j
public class HttpClientHelper {

    /**
     * 默认创建CloseableHttpClient
     * @return HttpClient
     */
    public static HttpClient createDefault(){
        return HttpClients.createDefault();
    }


    public static boolean checkClient(HttpClient httpClient){
        if (! Objects.nonNull(httpClient)){
            log.error("http Client is null");
            throw new RuntimeException("http Client is null");
        }else {
            return true;
        }
    }

    /**
     * 发送post 请求 结果以json 形式接收
     * @param requestBody 请求参数
     * @param contentType 返回类型
     * @param httpClient http客户端
     * @return result
     */
    public static JSONObject sendJsonPostRequest(String url,String header,HashMap<String,Object> requestBody, ContentType contentType, HttpClient httpClient){
        HttpPost httpPost = new HttpPost(url);
        if (Objects.nonNull(header) && header.length() > 0) {
            httpPost.setHeader("Content-Type", header);
        }
        StringEntity entity = new StringEntity(JSON.toJSONString(requestBody), contentType);
        httpPost.setEntity(entity);
        if (checkClient(httpClient)){
            try {
                HttpResponse response = httpClient.execute(httpPost);
                HttpEntity responseEntity = response.getEntity();
                if (Objects.nonNull(responseEntity)){
                    JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(responseEntity));
//                    JSON.isValid(); fastJson bug 不可用
                    if (! jsonObject.isEmpty()){
                        return jsonObject;
                    }
                }
            } catch (IOException  | JSONException e) {
                log.error("there is error in post request " + e.getMessage());
                e.printStackTrace();
            }
        }
        return new JSONObject();
    }

    /**
     * 发送get 请求 结果以json格式返回
     * @param url url
     * @param header  请求头
     * @param requestParams 请求参数列表
     * @param contentType contentType
     * @param httpClient 客户端
     * @return result
     */
    public static JSONObject sendJsonGetRequest(String url,String header,HashMap<String,Object> requestParams,ContentType contentType,HttpClient httpClient){
        URIBuilder uriBuilder = null;
        try {
            uriBuilder = new URIBuilder(url);
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        if (Objects.nonNull(requestParams) && requestParams.size() > 0){
            URIBuilder finalUriBuilder = uriBuilder;
            requestParams.forEach((key, value) -> {
                assert finalUriBuilder != null;
                finalUriBuilder.setParameter(key, String.valueOf(value));
            });
        }
        URI uri = null;
        try {
            assert uriBuilder != null;
            uri = uriBuilder.build();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        HttpGet httpGet = new HttpGet(uri);
        if ( Objects.nonNull(header) && header.length() > 0){
            httpGet.setHeader("Content-Type",header);
//                httpGet.setHeader("Accept-Charset", "UTF-8");
            httpGet.setHeader("Accept",contentType.getMimeType());
        }
        if (checkClient(httpClient)){
            try {
                HttpResponse response = httpClient.execute(httpGet);
                HttpEntity responseEntity = response.getEntity();
                if (Objects.nonNull(responseEntity)){
                    JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(responseEntity));
                    if (! jsonObject.isEmpty()){
                        return jsonObject;
                    }
                }
            }catch (IOException | JSONException e){
                log.error("there is error in get request " + e.getMessage());
                e.printStackTrace();
            }
        }
        return new JSONObject();
    }

    /**
     * 发送无参数或带有参数的get请求并将结果封装成json
     * @param url url
     * @param header 请求头
     * @param contentType contentType
     * @param httpClient 客户端
     * @return json
     */
    public static JSONObject sendJsonGetRequest(String url,String header,ContentType contentType,HttpClient httpClient){
        HttpGet httpGet = new HttpGet(url);
        if (Objects.nonNull(header) && header.length() > 0 ){
            httpGet.setHeader("Content-Type",header);
            httpGet.setHeader("Accept",contentType.getMimeType());
        }
        if (checkClient(httpClient)){
            try {
                HttpResponse response = httpClient.execute(httpGet);
                HttpEntity responseEntity = response.getEntity();
                if (Objects.nonNull(responseEntity)) {
                    JSONObject jsonObject = JSON.parseObject(EntityUtils.toString(responseEntity));
                    if (!jsonObject.isEmpty()) {
                        return jsonObject;
                    }
                }
            }catch (IOException | JSONException e){
                log.error("there is error in get request " + e.getMessage());
                e.printStackTrace();
            }
        }
        return new JSONObject();
    }


}
